﻿using Microsoft.Extensions.Caching.Memory;
using Models.Common;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace UtilsCache
{
    // //https://www.cnblogs.com/cpy-648412294/p/13034820.html
    public static class UtilMemoryCacheHelper
    {
        private static IMemoryCache _memoryCache = null;
        static UtilMemoryCacheHelper()
        {
            if (_memoryCache == null)
            {
                _memoryCache = new MemoryCache(new MemoryCacheOptions());
            }
        }
        public static void set(string key, object value)
        {
            //被动过期 （绝对时间过期）
            //var cacheopetions = new MemoryCacheEntryOptions()
            //{
            //    //设置过期时间（5秒）
            //    AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(exprireMins)
            //};
            ////设置过期回调函数
            //cacheopetions.RegisterPostEvictionCallback((key, value, reason, obj) =>
            //{
            //    Console.WriteLine(reason);
            //});
            _memoryCache.Set(key, value);
        }
        public static void set(string key, object value, int exprireSecond)
        {
            //被动过期 （绝对时间过期）
            //var cacheopetions = new MemoryCacheEntryOptions()
            //{
            //    //设置过期时间（5秒）
            //    AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(exprireMins)
            //};
            ////设置过期回调函数
            //cacheopetions.RegisterPostEvictionCallback((key, value, reason, obj) =>
            //{
            //    Console.WriteLine(reason);
            //});
            _memoryCache.Set(key, value, TimeSpan.FromSeconds(exprireSecond));
        }
        //public static void set(string key, object value, int exprireMins)
        //{
        //    //被动过期 （绝对时间过期）
        //    //var cacheopetions = new MemoryCacheEntryOptions()
        //    //{
        //    //    //设置过期时间（5秒）
        //    //    AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(exprireMins)
        //    //};
        //    ////设置过期回调函数
        //    //cacheopetions.RegisterPostEvictionCallback((key, value, reason, obj) =>
        //    //{
        //    //    Console.WriteLine(reason);
        //    //});
        //    _memoryCache.Set(key, value, TimeSpan.FromMinutes(exprireMins));
        //}
        public static void set<T>(string key, T value)
        {
            _memoryCache.Set(key, value);
        }
        public static void set<T>(string key, T value, int exprireSecond)
        {
            _memoryCache.Set(key, value, TimeSpan.FromSeconds(exprireSecond));
        }
        public static object get(string key)
        {
            return _memoryCache.Get(key);
        }
        public static T get<T>(string key)
        {
            return _memoryCache.Get<T>(key);
        }
        public static void remove(string key)
        {
            _memoryCache.Remove(key);
        }

        //不准确
        //public static void waitUnLock(string key)
        //{
        //    string lockobj = get<string>(key);
        //    while (lockobj != null)
        //    {
        //        lockobj = get<string>(key);
        //        Thread.Sleep(50);
        //    }
        //}
        //public static void setLock(string key)
        //{
        //    set(key, "true", 60);
        //}
        //public static void setDelLock(string key)
        //{
        //    remove(key);
        //}

        /// <summary>
        /// 存储一个对象（该对象会被序列化保存）
        /// </summary>
        /// <param name="redisKey">名称</param>
        /// <param name="redisValue">值</param>
        /// <param name="expiry">时间</param>
        /// <returns></returns>
        public static bool StringSet<T>(string redisKey, T redisValue, int min = 30)
        {


            //return UtilMemoryCacheHelper.set<T>(redisKey, redisValue, min);
            TimeSpan expiry = new TimeSpan(0, min, 0);
            var json = JsonConvert.SerializeObject(redisValue);// Serialize(redisValue);

            UtilMemoryCacheHelper.set<string>(redisKey, json, min * 60);
            return true;
            //return UtilMemoryCacheHelper.set(redisKey, json, min);
            // return _DB.StringSet(redisKey, json, expiry);
        }

        /// <summary>
        /// 获取一个对象（会进行反序列化）
        /// </summary>
        /// <param name="redisKey">名称</param>
        /// <param name="expiry">时间</param>
        /// <returns></returns>
        public static T StringGet<T>(string redisKey, TimeSpan? expiry = null)
        {
            string result = UtilMemoryCacheHelper.get<string>(redisKey);
            //  string result = UtilMemoryCacheHelper.get<string>(redisKey);
            if (!string.IsNullOrEmpty(result))
            {
                return JsonConvert.DeserializeObject<T>(result);
            }
            return default(T);

        }

    }
}
